package com.hk.springtrains.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;

@Controller
public class TrainsController {

    private static Logger logger = LoggerFactory.getLogger(TrainsController.class);

    @Autowired
    private WebSocketHandlerWithSimpTemplate template;

    /**
     * 默认情况下，帧发往的目的地与触发处理方法的目的他相同，只不过需要添加"/topic前缀",则本例中发往目的地为"/topic/async"
     * @param incoming
     * @return
     */
    @MessageMapping(value = "/async")
    public Msg handleMsg(Msg incoming){
        logger.info("Received message:"+incoming);
        incoming.setMessage("This is coming from server");
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return incoming;
    }


    /**
     * 也可以通过@SendTo指定发往目的地
     * @param incoming
     * @return
     */
    @MessageMapping(value = "/async2")
    @SendTo(value = "/topic/myDestination")
    public Msg handleMsg2(Msg incoming){
        logger.info("Received message:"+incoming);
        incoming.setMessage("This is coming from server");
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return incoming;
    }


    /**
     * 使用@SubscribeMapping注解时，消息默认不经过代理，直接返回。
     * 此时此例中客户端的订阅地址为"/app/sync3"而非"/topic/sync3",处理场景为订阅后给与反馈。
     * 也可以通过@SendTo注解，重新设置该行为，使其经过消息代理
     * @return
     */
    @SubscribeMapping(value = "/async3")
    public Msg handleMsg3(){
       // logger.info("Received message:"+incoming);
        Msg temp = new Msg();
        temp.setMessage("订阅成功");
        //incoming.setMessage("This is coming from server");
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i=0;i<100;i++){
                    Msg msg = new Msg();
                    msg.setMessage("From SimpTemplate "+i);
                    System.out.println("From SimpTemplate "+i);
                    template.sendMessage(msg);
                }
            }
        }).start();

        System.out.println("Do");
        return temp;
    }




    //stompTemplate
    //@SendToUser




}
